#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
B站视频信息获取模块
参考：https://zhuanlan.zhihu.com/p/630522012
"""

import requests
import re
import json
from typing import Dict, Optional, Any
from .config import HEADERS


class BiliVideoFetcher:
    """B站视频信息获取器"""
    
    def __init__(self):
        self.headers = {
            'referer': 'https://www.bilibili.com/',
            'user-agent': HEADERS.get('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36')
        }
    
    def extract_bvid(self, url: str) -> Optional[str]:
        """从B站视频URL中提取BVID"""
        pattern = r'BV[a-zA-Z0-9]+'
        match = re.search(pattern, url)
        return match.group() if match else None
    
    def get_video_info(self, url: str) -> Dict[str, Any]:
        """获取B站视频基本信息
        
        Args:
            url: B站视频URL，如 https://www.bilibili.com/video/BV1xx411c7mD
            
        Returns:
            包含视频信息的字典
        """
        bvid = self.extract_bvid(url)
        if not bvid:
            raise ValueError("无法从URL中提取BVID")
        
        # 获取视频页面HTML
        try:
            response = requests.get(url, headers=self.headers, timeout=15)
            response.raise_for_status()
            html_content = response.text
            
            # 从HTML中提取视频信息
            video_info = self._parse_video_info(html_content, bvid)
            return video_info
            
        except requests.RequestException as e:
            raise Exception(f"请求失败: {e}")
    
    def _parse_video_info(self, html_content: str, bvid: str) -> Dict[str, Any]:
        """解析HTML内容，提取视频信息"""
        info = {
            'bvid': bvid,
            'title': '',
            'author': '',
            'duration': '',
            'view_count': 0,
            'danmaku_count': 0,
            'like_count': 0,
            'coin_count': 0,
            'favorite_count': 0,
            'share_count': 0,
            'description': '',
            'upload_time': '',
            'tags': [],
            'video_url': f'https://www.bilibili.com/video/{bvid}'
        }
        
        try:
            # 提取标题
            title_match = re.search(r'<title[^>]*>([^<]+)', html_content)
            if title_match:
                info['title'] = title_match.group(1).replace('_哔哩哔哩_bilibili', '').strip()
            
            # 提取window.__INITIAL_STATE__中的数据
            initial_state_match = re.search(r'window\.__INITIAL_STATE__\s*=\s*({.+?});', html_content)
            if initial_state_match:
                try:
                    initial_state = json.loads(initial_state_match.group(1))
                    video_data = initial_state.get('videoData', {})
                    
                    if video_data:
                        info.update({
                            'title': video_data.get('title', info['title']),
                            'author': video_data.get('owner', {}).get('name', ''),
                            'duration': video_data.get('duration', 0),
                            'description': video_data.get('desc', ''),
                            'upload_time': video_data.get('pubdate', 0)
                        })
                        
                        # 统计数据
                        stat = video_data.get('stat', {})
                        info.update({
                            'view_count': stat.get('view', 0),
                            'danmaku_count': stat.get('danmaku', 0),
                            'like_count': stat.get('like', 0),
                            'coin_count': stat.get('coin', 0),
                            'favorite_count': stat.get('favorite', 0),
                            'share_count': stat.get('share', 0)
                        })
                        
                        # 标签
                        tags = video_data.get('tag', [])
                        if isinstance(tags, list):
                            info['tags'] = [tag.get('tag_name', '') for tag in tags if isinstance(tag, dict)]
                        
                except json.JSONDecodeError:
                    pass
            
        except Exception as e:
            print(f"解析视频信息时出错: {e}")
        
        return info
    
    def get_video_download_urls(self, url: str) -> Dict[str, Any]:
        """获取视频下载链接（需要进一步的API调用）
        
        注意：B站的视频下载需要更复杂的处理，包括登录状态、防盗链等
        这里只提供基础框架
        """
        bvid = self.extract_bvid(url)
        if not bvid:
            raise ValueError("无法从URL中提取BVID")
        
        # 这里需要调用B站的API获取视频流信息
        # 由于涉及到复杂的认证和防盗链机制，这里只返回基础信息
        return {
            'bvid': bvid,
            'message': '视频下载功能需要进一步开发，涉及B站API认证和防盗链处理',
            'video_url': f'https://www.bilibili.com/video/{bvid}'
        }


def get_bili_video_info(url: str) -> Dict[str, Any]:
    """获取B站视频信息的便捷函数
    
    Args:
        url: B站视频URL
        
    Returns:
        视频信息字典
    """
    fetcher = BiliVideoFetcher()
    return fetcher.get_video_info(url)


def get_bili_video_download_urls(url: str) -> Dict[str, Any]:
    """获取B站视频下载链接的便捷函数
    
    Args:
        url: B站视频URL
        
    Returns:
        下载链接信息字典
    """
    fetcher = BiliVideoFetcher()
    return fetcher.get_video_download_urls(url)


if __name__ == "__main__":
    # 测试代码
    test_url = "https://www.bilibili.com/video/BV13M4y1t7PE"
    try:
        info = get_bili_video_info(test_url)
        print("视频信息:")
        for key, value in info.items():
            print(f"{key}: {value}")
    except Exception as e:
        print(f"获取视频信息失败: {e}")